package com.cjt.security;

import cn.hutool.core.util.ObjectUtil;
import com.cjt.pojo.User;
import com.cjt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user= userService.getByUsername(username);
        if (ObjectUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("用户名错误");
        }
        //把账号、密码、权限信息交给Security框架管理
        return new AccountUser(user.getId(),user.getUsername(),user.getPassword(),getUserAuthority(user.getId()));
    }

    //获取用户权限信息(角色，菜单权限)
    public List<GrantedAuthority> getUserAuthority(Long userId) {
        //通过userid查询该用户的角色编码 以及 菜单操作编码
        String authority = userService.getUserAuthorityInfo(userId);
        //通过工具类整合
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
